package primetest.impl.controler;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.component.datatable.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import primetest.dto.MedicineDto;
import primetest.faces.MedicineListModel;
import primetest.impl.manager.SessionManager;
import primetest.impl.service.MedicineService;

@Named("medicineListControler")
@SessionScoped
public class MedicineListControler implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = -2341239310873546662L;

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Inject
	private SessionManager sessionManager;

	private MedicineListModel medicineList = null;
	private List<MedicineDto> baseMedicineList;
	private MedicineDto selectedMedicine = new MedicineDto();
	private MedicineDto backMedicine = new MedicineDto();
	private MedicineDto newMedicine = new MedicineDto();
	private int first;
	private boolean editMode = false;
	private boolean addMode = false;

	private List<MedicineDto> filteredTerms;

	public boolean getEditMode() {
		return editMode;
	}

	public boolean getAddMode() {
		return addMode;
	}

	@Inject
	private MedicineService medicineService;

	public MedicineListModel getMedicineList() {
		if (baseMedicineList == null) {
			try {
				baseMedicineList = medicineService.getMedicineList();
				medicineList = new MedicineListModel(baseMedicineList);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}

		return baseMedicineList == null ? new MedicineListModel(
				new ArrayList<MedicineDto>()) : medicineList;
	}

	public void deleteMedicine() throws IOException {
		medicineService.deleteMedicine(selectedMedicine.getKey());
		// DataTable dataTable = (DataTable)
		// FacesContext.getCurrentInstance().getViewRoot()
		// .findComponent(":form01:medicineTable");
		// dataTable.resetValue();
	}

	public void reload() {
		baseMedicineList = null;
	}

	public MedicineDto getSelectedMedicine() {
		return selectedMedicine;
	}

	public void setSelectedMedicine(MedicineDto selectedMedicine) {
		this.selectedMedicine = selectedMedicine;
	}

	public int getFirst() {
		return first;
	}

	public void setFirst(int first) {
		this.first = first;
	}

	public MedicineDto getNewMedicine() {
		return newMedicine;
	}

	public void setNewMedicine(MedicineDto newMedicine) {
		this.newMedicine = newMedicine;
	}

	public void startEditMedicine() {
		editMode = true;
		backMedicine.setAll(selectedMedicine);
	}

	public void saveEditMedicine() {
		try {
			if (selectedMedicine.isValid()) {
				medicineService.updateMedicine(selectedMedicine);
				editMode = false;
			} else {
				sessionManager.addGlobalMessageFatal("Quantity invalid", null);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void cancelEditMedicine() {
		editMode = false;
		selectedMedicine.setAll(backMedicine);
	}

	public void startAddMedicine() {
		addMode = true;
		newMedicine = new MedicineDto();
	}

	public void addNewMedicine() throws IOException {
		if (newMedicine.isValid()) {
			medicineService.addMedicine(newMedicine);
			addMode = false;
			// DataTable dataTable = (DataTable)
			// FacesContext.getCurrentInstance().getViewRoot()
			// .findComponent(":form01:medicineTable");
			// dataTable.resetValue();
		} else {
			sessionManager.addGlobalMessageFatal("Quantity invalid", null);
		}
	}

	public void cancelAddMedicine() {
		addMode = false;
		newMedicine = new MedicineDto();
	}

	public List<MedicineDto> getFilteredTerms() {
		return filteredTerms;
	}

	public void setFilteredTerms(List<MedicineDto> filteredTerms) {
		this.filteredTerms = filteredTerms;
	}

	public boolean isNewRequest() {
		final FacesContext fc = FacesContext.getCurrentInstance();
		final boolean getMethod = ((HttpServletRequest) fc.getExternalContext()
				.getRequest()).getMethod().equals("GET");
		final boolean ajaxRequest = fc.getPartialViewContext().isAjaxRequest();
		final boolean validationFailed = fc.isValidationFailed();
		return getMethod && !ajaxRequest && !validationFailed;
	}

	public void onPageLoad() {
		if (isNewRequest()) {
			System.err.println("new request called");
		}

		DataTable dt1 = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("form01:medicineTable");
		dt1.reset();
		dt1.resetValue();
		dt1.setFilters(null);
		dt1.setValueExpression("sortBy", null);
		System.err.println("onPageLoad called");
    }
}
